package cn.felord.app.security;

import cn.felord.app.data.RestBody;
import cn.felord.app.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt 端点
 *
 * @author dax
 */
@Slf4j
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {

        if (response.isCommitted()) {
            log.debug("Response has already been committed");
            return;
        }

        Map<String, Object> map = new HashMap<>(8);
        map.put("time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        map.put("uri", request.getAttribute("javax.servlet.error.request_uri"));

        ResponseUtil.responseJsonWriter(response, RestBody.build(HttpServletResponse.SC_UNAUTHORIZED, map, "U ARE UNAUTHORIZED", "-9999"));
    }
}
